<template>
  <div>
    <div v-if="config.type === 'binary'">
      <van-cell :title="config.label">
        <img width="40px" align="left" :src="getImage(config, data)">
      </van-cell>
    </div>

    <div v-else-if="config.type === 'text'">
      <van-field
        autosize
        type="textarea"
        readonly
        :value="data[config.name]"
        :label="config.label"
      />
    </div>

    <div v-else-if="config.type === 'monetary'">
      <van-field
        :value="`¥ ${data[config.name]}`"
        :label="config.label"
        readonly
      />
    </div>

    <div v-else-if="config.type === 'boolean'">
      <van-field
        :value="data[config.name] ? '是' : '否'"
        :label="config.label"
        readonly
      />
    </div>

    <div v-else-if="['many2one', 'selection'].includes(config.type)">
      <van-field
        :value="data[`${config.name}__name`]"
        :label="config.label"
        readonly
      />
    </div>

    <div v-else-if="['one2many', 'many2many'].includes(config.type)">
      <!-- o2m or m2m field, multi select -->
      <van-field
        v-if="config.selected"
        :value="data[`${config.name}__names`]"
        :label="config.label"
        readonly
      />

      <div v-else>
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item
            :title="config.label"
            name="1"
            :value="data[`${config.name}__count`]"
          >
            <ViewO2m :data="data[`${config.name}__objects`]" :config="config" />
          </van-collapse-item>
        </van-collapse>
      </div>
    </div>

    <van-field
      v-else
      :value="data[config.name]"
      :label="config.label"
      readonly
    />
  </div>
</template>

<script>
import ViewO2m from './ViewO2m'

const get_image = (model, res_id, field) => {
  const baseURL = process.env.VUE_APP_BASE_API
  const imgUrl = '/web/image'
  if (!res_id) {
    return ''
  }
  return `${baseURL}${imgUrl}?model=${model}&id=${res_id}&field=${field}`
}

export default {
  name: 'FieldCell',
  components: { ViewO2m },
  props: {
    model: { type: String, default: undefined },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      activeName: '1'
    }
  },

  computed: {},

  watch: {},

  async created() {
    //
  },

  async mounted() {
    // console.log('ViewCell, config,', this.config.name, this.config)
  },

  methods: {
    getImage(fld, data) {
      // console.log('getImage,', this.model, fld, data)
      return get_image(this.model, data.id, fld.name)
    }
  }
}
</script>

<style type="text/css"></style>
